package org.example.ui;

import com.toedter.calendar.JDateChooser;
import org.example.dao.AttendanceDao;
import org.example.dao.impl.AttendanceImpl;
import org.example.entity.Attendance;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.List;

public class AttendanceManagementPanel extends JPanel {
    private AttendanceDao attendanceDao = new AttendanceImpl();
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField empIdField, workHoursField, overHoursField;
    private JDateChooser dateChooser;
    private JButton addButton;
    private JFrame parentFrame; // 存储父窗口引用

    public AttendanceManagementPanel() {
        // 移除窗口相关设置，改为普通面板初始化
        setLayout(new BorderLayout());

        // 初始化组件
        initComponents();

        // 加载考勤数据
        loadAttendanceData();
    }

    // 新增：设置父窗口引用，用于对话框定位
    public void setParentFrame(JFrame parentFrame) {
        this.parentFrame = parentFrame;
    }

    private void initComponents() {
        // 创建顶部输入面板
        JPanel inputPanel = new JPanel(new FlowLayout());
        JLabel empIdLabel = new JLabel("员工ID:");
        empIdField = new JTextField(10);

        JLabel dateLabel = new JLabel("日期:");
        dateChooser = new JDateChooser();

        JLabel workHoursLabel = new JLabel("工作时长:");
        workHoursField = new JTextField(5);

        JLabel overHoursLabel = new JLabel("加班时长:");
        overHoursField = new JTextField(5);

        addButton = new JButton("添加考勤");
        addButton.addActionListener(new AddButtonListener());

        inputPanel.add(empIdLabel);
        inputPanel.add(empIdField);
        inputPanel.add(dateLabel);
        inputPanel.add(dateChooser);
        inputPanel.add(workHoursLabel);
        inputPanel.add(workHoursField);
        inputPanel.add(overHoursLabel);
        inputPanel.add(overHoursField);
        inputPanel.add(addButton);

        // 创建表格
        tableModel = new DefaultTableModel(
                new String[]{"考勤ID", "员工ID", "日期", "工作时长", "加班时长"},
                0
        );
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // 添加组件到主面板
        add(inputPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }

    private void loadAttendanceData() {
        // 清空表格
        tableModel.setRowCount(0);

        // 查询所有考勤记录
        List<Attendance> attendanceList = attendanceDao.queryAllAttendance();

        // 添加数据到表格
        for (Attendance attendance : attendanceList) {
            tableModel.addRow(new Object[]{
                    attendance.getAttId(),
                    attendance.getEmpId(),
                    attendance.getAttendanceDate(),
                    attendance.getWorkHours(),
                    attendance.getOverHours()
            });
        }
    }

    private class AddButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                // 获取输入值
                int empId = Integer.parseInt(empIdField.getText());
                java.util.Date selectedDate = dateChooser.getDate();
                double workHours = Double.parseDouble(workHoursField.getText());
                double overHours = Double.parseDouble(overHoursField.getText());

                // 生成新的考勤ID
                int newAttId = generateNewAttendanceId();

                // 调用DAO添加考勤记录
                boolean success = attendanceDao.addAttendance(
                        newAttId,
                        empId,
                        selectedDate,
                        workHours,
                        overHours
                );

                if (success) {
                    // 使用父窗口作为对话框的父组件
                    JOptionPane.showMessageDialog(
                            parentFrame != null ? parentFrame : AttendanceManagementPanel.this,
                            "考勤记录添加成功！",
                            "成功",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                    // 刷新表格数据
                    loadAttendanceData();
                    // 清空输入框
                    clearInputFields();
                } else {
                    JOptionPane.showMessageDialog(
                            parentFrame != null ? parentFrame : AttendanceManagementPanel.this,
                            "考勤记录添加失败！",
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(
                        parentFrame != null ? parentFrame : AttendanceManagementPanel.this,
                        "请输入有效的数字！",
                        "输入错误",
                        JOptionPane.ERROR_MESSAGE
                );
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(
                        parentFrame != null ? parentFrame : AttendanceManagementPanel.this,
                        "发生错误: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            }
        }

        private int generateNewAttendanceId() {
            // 简单实现：获取当前最大ID加1
            List<Attendance> attendanceList = attendanceDao.queryAllAttendance();
            int maxId = 0;
            for (Attendance attendance : attendanceList) {
                if (attendance.getAttId() > maxId) {
                    maxId = attendance.getAttId();
                }
            }
            return maxId + 1;
        }

        private void clearInputFields() {
            empIdField.setText("");
            dateChooser.setDate(null);
            workHoursField.setText("");
            overHoursField.setText("");
        }
    }
}